import React, { FC, useState, useEffect } from 'react'
import { Form, Input, Button, Modal, message, Select } from 'antd'

import ProductionVoucher from '~/components/production-voucher'
import { useNavigate, useLocation } from 'react-router-dom'
import TopHeader, { ListTitle } from '~/components/top-header'
import SuccessModal from '~/components/submit-successfully'
import {
  queryCastItems,
  handleUpdateWhereabouts,
  handleCancelInform,
  handleConfirmInform
} from '~/api/accept-property-api'
import { formatTime } from '~/utils/utils'
import { HandleItemsMap } from '~/constants'

import WaitingList from './container/waiting-list'
import MovedList from './container/moved-list'
import { FooterAction } from './styled'

const { Option } = Select

const { TextArea } = Input

const isSpecializedStaff = JSON.parse(localStorage.getItem('u')!).roles.includes('KEEPER')

const PropertyInvolved: FC = () => {
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const { state }: any = useLocation()
  const [certificateVisible, setCertificateVisible] = useState(false)
  const [whereaboutsVisible, setWhereaboutsVisible] = useState(false)
  const [isShowRemark, setIsShowRemark] = useState(false)
  const [successVisible, setSuccessVisible] = useState(false)
  const [selectItems, setSelectItems] = useState([])
  const [castItems, setCastItems] = useState([])
  const { validateFields } = form

  console.log('caseCompanyName=>', state)
  const { caseName, caseNo, caseState, createTime, batchNo } = state

  const isWait = caseState === 1

  const handleGetCastItems = async () => {
    const { data = [], code } = await queryCastItems({
      batchNo,
      statusList: isWait ? ['WAIT'] : ['SUCCESS']
    })
    setCastItems(data)
    return code
  }

  const onClickSaveSetting = async () => {
    const { whereabouts, whereaboutsRemark } = await validateFields()
    await handleUpdateWhereabouts({
      serialNos: selectItems,
      whereabouts,
      whereaboutsRemark
    })
    setWhereaboutsVisible(false)
    handleGetCastItems()
  }

  const onClickCancelInform = async () => {
    if (!selectItems.length) return message.error('请至少选择一个物品')
    await handleCancelInform({
      batchNo,
      serialNos: selectItems
    })
    const code = await handleGetCastItems()
    code === '000202' ? navigate(-1) : message.success('撤销告知成功')
  }

  const onClickNotification = async (preview?: boolean) => {
    const { data } = await handleConfirmInform({
      batchNo,
      caseName,
      caseNo,
      docs: [
        {
          name: 'string',
          storeId: 'string'
        }
      ],
      paperDir: 0,
      preview: !!preview
    })
    window.open(data.url)
    if (preview) return
    setSuccessVisible(true)
  }

  useEffect(() => {
    handleGetCastItems()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const headData = [
    {
      childen: [
        {
          label: '案件编号:',
          value: caseNo
        },
        { label: '案件名称:', value: caseNo }
      ]
    },
    {
      childen: [
        { label: '移交时间:', value: formatTime(createTime) },
        { label: '批次号:', value: batchNo }
      ]
    }
  ]

  return (
    <div>
      <TopHeader headData={headData} />
      <ListTitle />
      <main style={{ marginTop: 21 }}>
        {isWait && isSpecializedStaff && (
          <Button
            style={{ marginBottom: 10 }}
            type="primary"
            onClick={() => {
              if (!selectItems.length) return message.error('请至少选择一个物品')
              setWhereaboutsVisible(true)
            }}
          >
            批量设置采集物品去向
          </Button>
        )}

        {isWait ? (
          <WaitingList castItems={castItems} selectItems={selectItems} setSelectItems={setSelectItems} />
        ) : (
          <MovedList castItems={castItems} />
        )}
        <FooterAction>
          {isWait ? (
            <div>
              <Button type="primary" danger onClick={onClickCancelInform}>
                撤销告知
              </Button>
              <Button
                onClick={() => {
                  navigate(-1)
                }}
                style={{ marginLeft: 8 }}
              >
                返回
              </Button>
              <Button
                onClick={() => {
                  onClickNotification(true)
                }}
                style={{ marginLeft: 8 }}
              >
                预览告知凭证
              </Button>
              <Button
                onClick={() => {
                  onClickNotification()
                }}
                style={{ marginLeft: 8 }}
                type="primary"
              >
                制作告知凭证
              </Button>
            </div>
          ) : (
            <>
              <Button
                onClick={() => {
                  navigate(-1)
                }}
                style={{ marginLeft: 8 }}
              >
                返回
              </Button>
            </>
          )}
        </FooterAction>
      </main>
      <ProductionVoucher
        onCancel={() => {
          setCertificateVisible(false)
        }}
        visible={certificateVisible}
      />
      <Modal
        visible={whereaboutsVisible}
        onOk={onClickSaveSetting}
        onCancel={() => {
          setWhereaboutsVisible(false)
        }}
      >
        <Form validateTrigger="onBlur" form={form} style={{ marginTop: 36 }}>
          <Form.Item name="whereabouts" label="物品去向">
            <Select
              onChange={val => {
                setIsShowRemark(val === 'OTHER')
              }}
            >
              {[...HandleItemsMap].map(([key, value], index) => (
                <Option key={index} value={key}>
                  {value}
                </Option>
              ))}
            </Select>
          </Form.Item>
          {isShowRemark && (
            <Form.Item name="whereaboutsRemark" label="备注">
              <TextArea placeholder="请输入备注" />
            </Form.Item>
          )}
        </Form>
      </Modal>
      <SuccessModal visible={successVisible} />
    </div>
  )
}

export default PropertyInvolved
